<template>
  <div>
    <h1>{{ postDetail.auther }}</h1>
    <h4>{{ postDetail.datetime }}</h4>
    <h3>{{ postDetail.title }}</h3>
    <p>
      {{ postDetail.desc }}
    </p>
    <!-- 评论 -->
    <el-input
      v-model="textarea"
      :rows="5"
      type="textarea"
      placeholder="请输入评论"
      @focus="onValidLogin"
    />

    <el-button type="primary" @click="addMess">评论</el-button>

    <!-- 评论列表 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>评论列表</span>
        </div>
      </template>
      <div v-for="v in postDetail.mess" :key="v.id" class="text item">
        <p>
          <img :src="v.avator" alt="" />|
          <b>{{ v.nickname }}</b>|
          <span>{{ v.datetime }}</span>
        </p>
        <p>
          {{ v.content }}
        </p>
      </div>
    </el-card>
  </div>
</template>


<script>
import { ElMessage } from 'element-plus'
// import { computed } from '@vue/reactivity'
import { useRoute, useRouter } from "vue-router";
// import { useStore } from 'vuex'
import axios from "axios";
import { ref } from "@vue/reactivity";
import { onMounted } from "@vue/runtime-core";
export default {
  setup() {
    const route = useRoute();
    const router = useRouter()
    // const store = useStore()
    const { id } = route.params;
    const textarea = ref('')
    // 详情数据
    const postDetail = ref({});
    // 请求详情方法
    const getPostDetail = async id => {
      const resp = await axios.post("/post/detail", { id });
      postDetail.value = resp.data.data;
    };
    // 验证登录函数
    const onValidLogin = () => {
      if(!localStorage.getItem('token')) {
        router.push({ name: 'login' })
      }
    }
    // 添加评论
    const addMess = () => {
      const item = {
        "avator": require('@/assets/logo.png'),
        "nickname": localStorage.getItem('token'),
        "datetime": new Date().toLocaleString(),
        "content": textarea.value , 
        "zan": 0,
        "id": new Date().getTime().toString()
      }

      postDetail.value.mess.unshift(item)
      textarea.value = ""
      ElMessage({
        message: '评论成功！',
        type: 'success',
      })

    }
    // const postDetail = computed(() =>
    //   store.getters.postDetail(id)
    // )


    onMounted(() => {
      // 请求
      getPostDetail(id);
    });

    return {
      postDetail,
      textarea,
      onValidLogin,
      addMess
    };
  }
};
</script>


<style scoped lang="scss">
.item {
  p {
    line-height: 36px;
    display: flex;
    align-items: center;
    img {
      width: 20px;
      border-radius: 50%;
    }
  }
}
</style>